import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { RbacUserService } from './rbac_user/rbac_user.service';
import { RbacPermission } from './rbac_user/entities/rbac_permission.entity';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RbacPermissionGuard implements CanActivate {

  @Inject(RbacUserService)
  private rbacUserService: RbacUserService

  @Inject(Reflector)
  private reflector: Reflector
  
  async canActivate(
    context: ExecutionContext,
  ): Promise<boolean> {
    const request = context.switchToHttp().getRequest()
    if (!request.user) {
      return true
    }    
    const roles = await this.rbacUserService.findRolesByIds(request.user.roles.map(item => item.id))
    const permissions: RbacPermission[] = roles.reduce((total, current) => {
      total.push(...current.permissions)
      return total
    }, [])
    console.log(permissions)

    const requiredPermissions = this.reflector.getAllAndOverride('require-permission', [
      context.getClass(),
      context.getHandler()
    ])

    console.log(requiredPermissions)

    for (let i = 0; i < requiredPermissions.length; i++) {
      const curPermission = requiredPermissions[i]
      const found = permissions.find(item => item.name === curPermission)
      if (!found) {
        throw new UnauthorizedException('您没有访问该接口的权限')
      }      
    }

    return true;
  }
}
